%{
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#include <yirae/ylist.h>
#include <yirae/ystring.h>

char* ip = NULL;
char* remote_ip = NULL;
char* local_ip = NULL;
int port = -1;
char* ports = "-1";
yList ports_list;

char* parser_get_remote_ip()
{
	return remote_ip;
}

int parser_get_remote_port()
{
	return port;
}

char* parser_get_local_ip()
{
	return local_ip;
}

yList parser_get_local_ports()
{

	yList ilist = ylist_new();
	yString s = ystring_new(255);
	ystring_set(&s, 255, ports);
	yList slist =  ystring_split(s, 255, ",");

	int i;
	for(i = 0; i < ylist_length(slist); i++) {
		ylist_int_append(ilist, atoi(ylist_data_get(slist, i)));
	}

	return ilist;
	
}

void yyerror(const char *str)
{
	fprintf(stderr, "error: %s\n", str);
}

int yywrap()
{
	return 1;
}

%}

%union
{
	int number;
	char *string;
}

%token KEYWORD_REMOTE KEYWORD_LOCAL KEYWORD_IP KEYWORD_PORT KEYWORD_PORTS BRACE_OPEN BRACE_CLOSE /*OPERATOR_ASSIGNMENT SEMICOLON*/

%token <string> IP_ADDR 
%token <string> PORTS_LIST 
%token <string> WORD
%token <number> NUMBER 

%%
commands:
		| commands command
		;

command:
	   remote_set
	   |
	   local_set
	   ;

remote_set:
		KEYWORD_REMOTE remote_block
		{
			if(ip) {
				remote_ip = strdup(ip);
				free(ip);
				ip = NULL; /* reset so we can reuse */
			}
		}
		;

local_set:
		KEYWORD_LOCAL local_block
		{
			if(ip) {
				local_ip = strdup(ip);
				free(ip);
				ip = NULL;
			}
		}
		;

remote_block:
		'{' remote_options '}'
		;

local_block:
	   '{' local_options '}'
	   ;

remote_options:
		| remote_options remote_option
		;

local_options:
		| local_options local_option
		;

remote_option:
		port_assignment
		| 
		ip_assignment
		;

local_option:
		ip_assignment
		| 
		ports_list_assignment
		;

ip_assignment:
		KEYWORD_IP '=' IP_ADDR ';'
		{
			ip = $3;
		}
		;

port_assignment:
		KEYWORD_PORT '=' NUMBER ';'
		{
			port = $3;
		}
		;

ports_list_assignment:
		KEYWORD_PORTS '=' PORTS_LIST ';'
		{
			ports = $3;
		}
		;
%%
